//
//  Earnest_PayViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/6/29.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "Earnest_PayViewController.h"
#import "Common.h"
#import <Pingpp.h>

#import "PayViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "WKProgressHUD.h"
#import <Masonry.h>
#define kUrlScheme  @"demoapp001" // 这个是你定义的 URL Scheme，支付宝、微信支付、银联和测试模式需要。
#define kUrlWX  @"wx5f0250600950a712"


@interface Earnest_PayViewController ()<CLLocationManagerDelegate>
{
    Common * com;
}
@property (nonatomic,strong) CLLocationManager *locationManage;
@property (nonatomic,copy) NSString *cityName;

@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) UIView *payView;
@property (nonatomic) BOOL isAgree;
@property (nonatomic) int rowNumber;
@property (nonatomic,strong) UILabel *activityLabel;
@property (nonatomic,strong) UILabel * priceAllLabel;//折扣前费用
@property (nonatomic,strong) UIView * priceAllLine;
@property (nonatomic,strong) UIButton *payButton;



@property (nonatomic,strong) UILabel *moneyL;
@property (nonatomic,strong) WKProgressHUD *hud;



@end

@implementation Earnest_PayViewController

- (instancetype)init

{
    self = [super init];
    if (self) {
        self.quoteid = [[NSString alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataDictionary = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    
    com = [[Common alloc]init];
    _priceAllLabel = [com createUIlabel:@"" andFont:FontOfSize12 andColor:carScrollColor];
    _priceAllLine = [[UIView alloc]init];
    _activityLabel = [com createUIlabel:@"" andFont:FontOfSize12 andColor:YellowColor];
    

    
//    [self locate];
    [self initDataSource];
    [self initSubView];
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
}



-(void)locate
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManage = [[CLLocationManager alloc]init];
        self.locationManage.delegate = self;
    } else {
        
        UIAlertController *alertV = [UIAlertController alertControllerWithTitle:@"提示" message:@"定位不成功，请确认开启定位" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];

        [alertV addAction:action1];
        [alertV addAction:action2];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }
    
    [self.locationManage startUpdatingLocation];
}

#pragma mark CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
                
                
            }
            
            self.cityName = city;
            self.cityLabel.text = [NSString stringWithFormat:@"%@",city];
            
//            else if (error == nil && [placemark copy] == 0)
//            
//                NSLog(@"No results were returned");
        }
        
    }];
    
    
    [self.locationManage stopUpdatingLocation];
}

-(void)initSubView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.priceView.frame) , screenWidth, cellHeight)];
    view.backgroundColor = WhiteColor;
    view.tag = 10000;
    [self.scrollView addSubview:view];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, screenWidth - 18, 0.5)];
    label.backgroundColor = LineGrayColor;
    [view addSubview:label];
    
    
//    _activityLabel = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth - 165 * kWidth, 0, 70 * kWidth, cellHeight)];
//    _activityLabel.tag = 301;
//    _activityLabel.textColor = YellowColor;
//    _activityLabel.font = Font(16);
//    _activityLabel.text = @"";
//    
    self.moneyL = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_activityLabel.frame), 0 , 80 * kWidth, cellHeight)];
    self.moneyL.font = Font(16);
    self.moneyL.textColor = YellowColor;
    self.moneyL.text = @"";
    self.moneyL.textAlignment = NSTextAlignmentRight;
    [view addSubview:self.moneyL];
    
    [view addSubview:_activityLabel];
    
    _payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (Main_height == 480 || Main_height ==568) {
        
    _payButton.frame = CGRectMake(18, CGRectGetMaxY(view.frame) + 20*kHeight, screenWidth - 36, Button_Height-10*kHeight) ;
    }else{
    _payButton.frame = CGRectMake(18, CGRectGetMaxY(view.frame) + 20*kHeight, screenWidth - 36, Button_Height) ;
    }
    
    [_payButton setTitle:@"确定支付" forState:UIControlStateNormal];
    _payButton.layer.cornerRadius = 5;
    [_payButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    _payButton.backgroundColor = YellowColor;
    [self.scrollView addSubview:_payButton];
    [_payButton addTarget:self action:@selector(payButtonAction) forControlEvents:UIControlEventTouchUpInside];
    _payButton.titleLabel.font = Font(17);
    
    
    self.scrollView.contentSize = CGSizeMake(screenWidth, CGRectGetMaxY(_payButton.frame) + 64 + 20 );


    
}

-(void)payButtonAction
{
    PayViewController *payVC = [[PayViewController alloc]init];
    
    payVC.quoteid = self.quoteid;
    payVC.orderid = self.orderId;
    payVC.orderNumber = self.numberLabel.text;
    payVC.moneyString = self.moneyL.text;
    
    [self.navigationController pushViewController:payVC animated:YES];
}

-(void)initDataSource
{
    
    NSString * quoteid = [NSString stringWithFormat:@"%@",self.quoteid];
    NSString *urlString = nil;
    if (quoteid.length>0) {
        
      urlString = [NSString stringWithFormat:@"%@?orderid=%ld&quoteid=%@",payment_info,[self.orderId integerValue],self.quoteid];
    }else{
      urlString = [NSString stringWithFormat:@"%@/%ld",order_detail,[self.orderId integerValue]];
    }
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        if ([responseObj[@"success"] boolValue]) {
                self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
                            
                [self getValueString];
        } else {
            
            
            [WKProgressHUD popMessage:[NSString stringWithFormat:@"%@",responseObj[@"message"]] inView:self.view duration:1.5 animated:YES];

        }
        
        
    } failed:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
    }];
}


-(void)getValueString
{
    /**
     订单
     */
    
    
    //订单
    self.numberLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"orderCode"]];
    //状态
    
//    self.statusLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"statusText"]];
    //起始地
    
    self.startLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"departCityName"]];
    //起始详情地址
    
    self.startDetailLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"departUnit"]];
    //起始日期
    
    self.startDate.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"deliveryDate"]];
    
    //目的地
    
    self.endLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"receiptCityName"]];
    //
    
    self.endDetailLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"receiptUnit"]];
    self.endDateLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"arriveDate"]];
    
    //车辆
    
    self.carLabel.text = @"";
    
    for (int i = 0; i < [self.dataDictionary[@"vehicles"] count]; i ++) {
        NSString *string = [NSString stringWithFormat:@"%@-%@-%@辆",self.dataDictionary[@"vehicles"][i][@"brandName"],self.dataDictionary[@"vehicles"][i][@"vehicleName"],self.dataDictionary[@"vehicles"][i][@"amount"]];
        
        self.carLabel.text = [self.carLabel.text stringByAppendingString:string];
        self.carLabel.text = [self.carLabel.text stringByAppendingString:@"   "];
        
    }
    
    [self.carLabel sizeToFit];
    self.carLabel.frame = CGRectMake(self.carLabel.frame.origin.x, self.carLabel.frame.origin.y, self.carLabel.frame.size.width, cellHeight);
    
    self.scrollV.contentSize = CGSizeMake(self.carLabel.frame.size.width, cellHeight);
    
    
    /**
     承运人
     */
    
        //姓名
        self.nameLabel.text = [self backString:self.dataDictionary[@"driverInfo"][@"name"]];
        
        //车牌
        self.carNumberLabel.text = [self backString:self.dataDictionary[@"driverInfo"][@"truckNo"]];
        
        //电话
        self.phoneLabel.text = [self backString:self.dataDictionary[@"driverInfo"][@"phone"]];
    
        //车型
        self.carStyleLabel.text = [self backString:self.dataDictionary[@"driverInfo"][@"truckType"]];
    
    /**
     物流
     */
    
    //提车费
    self.totalLabel.text = [self backMoney:self.dataDictionary[@"feeDetail"][@"extractcost"]];
    // 交车费
    self.payLabel.text = [self backMoney:self.dataDictionary[@"feeDetail"][@"returncost"]];
    
    //保险费
    self.unpayLabel.text = [self backMoney:self.dataDictionary[@"feeDetail"][@"insurance"]];
    //运输费
    self.scoreLabel.text = [self backMoney:self.dataDictionary[@"feeDetail"][@"shippingfee"]];
    
    //平台服务费
//    self.pingLabel.text = [self backMoney:self.dataDictionary[@"order"][@"feemap"][@"servicecharges"]];
    
    
    NSString * isdiscount = [NSString stringWithFormat:@"%@",_dataDictionary[@"feeDetail"][@"isdiscount"]];
    UIView * view = (UIView*)[self.view viewWithTag:10000];

    //优惠
    if ([isdiscount isEqualToString:@"T"]) {
        
        float total = [self.dataDictionary[@"feeDetail"][@"total"] floatValue];
        _priceAllLabel.text = [NSString stringWithFormat:@"￥%.2f",total];
        [view addSubview:_priceAllLabel];
        [_priceAllLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.moneyL.mas_left).with.offset(-16*kHeight);
            make.centerY.mas_equalTo(self.moneyL.mas_centerY);
        }];
        
        _priceAllLine.backgroundColor = BlackColor;
        [_priceAllLabel addSubview:_priceAllLine];
        [_priceAllLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_priceAllLabel.mas_left);
            make.right.equalTo(_priceAllLabel.mas_right);
            make.centerY.mas_equalTo(_priceAllLabel.mas_centerY);
            make.height.mas_equalTo(0.5);
        }];
        _activityLabel.text =  [NSString stringWithFormat:@"%@",self.dataDictionary[@"feeDetail"][@"desc"]];
        [view addSubview:_activityLabel];
        
        [_activityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.top.mas_equalTo(self.moneyL.mas_bottom).with.offset(3*kHeight);
        }];
    }else{
        _payButton.frame = CGRectMake(18, CGRectGetMaxY(view.frame) + 10*kHeight, screenWidth - 36, Button_Height) ;
    }
    self.moneyL.text = [self backMoney:_dataDictionary[@"feeDetail"][@"actualcost"]];
    [self.moneyL sizeToFit];
    self.moneyL.frame = CGRectMake(screenWidth - 15 - self.moneyL.frame.size.width, 0, self.moneyL.frame.size.width, cellHeight);
    
    UILabel *label = (UILabel *)[self.view viewWithTag:301];
    label.frame = CGRectMake(CGRectGetMinX(self.moneyL.frame) - 70 * kWidth, 0, 70 * kWidth, cellHeight);
    
    //当前定位城市
//    self.cityLabel.text = [self backString:self.dataDictionary[@"quote"][@"position"]];
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSString *)backString:(NSString *)string
{

    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}

-(NSString *)backMoney:(NSString *)string
{
    NSString   *str = [NSString stringWithFormat:@"%.2f",[string floatValue]];
    
    if ([str isEqual:[NSNull null]]) {
        return @"";
    } else {
        return [NSString stringWithFormat:@"￥%@",str];
    }

    
    }





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
